package cn.witsky.rtp2ws;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import cn.witsky.rtp2ws.domain.Message;
import cn.witsky.rtp2ws.push.retry.ReadTask;
import cn.witsky.rtp2ws.push.retry.RetryManager;
import cn.witsky.rtp2ws.util.RtpUtil;
import cn.witsky.rtp2ws.util.SystemClock;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class ByteBuffTest {
	static Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.SECONDS).build();
	private static Logger logger = LoggerFactory.getLogger(ByteBuffTest.class);

// sudo java -server -Xms4g -Xmx4g -Xloggc:rtp2ws-gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -Dcom.sun.management.jmxremote.port=9008 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=192.168.150.39 -jar rtp2ws-0.0.1-SNAPSHOT.jar
// sudo java -server -Xms4g -Xmx4g -Xloggc:rtp2ws-gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseG1GC  -Dcom.sun.management.jmxremote.port=9008 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=192.168.150.39 -jar rtp2ws-0.0.1-SNAPSHOT.jar
	public static void main(String[] args) throws InterruptedException {
		System.out.println("bakup:call:4361931329095350".length());
	    String[] str1 = {"Hello","world","java"};
	    String[] str2 = {"Veriable","syntax","interator"};
	    int str1Length = str1.length;
	    int str2length = str2.length;
	        
	    str1 = Arrays.copyOf(str1, str1Length+str2length);//数组扩容
	    System.arraycopy(str2, 0, str1, str1Length, str2length);
	    System.out.println(Arrays.toString(str1));
		
		
		DateTimeFormatter fmTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		// 当前时间
		LocalDateTime now = LocalDateTime.now();
		System.out.println("当前时间:" + now.format(fmTime));
//        /*******************初始阶段**********************/
//        ByteBuf buf = Unpooled.buffer(100, 200);
//        System.out.println("writable bytes " + buf.writableBytes());
//        System.out.println("readable bytes " + buf.readableBytes());
//
//        /*******************写入数据**********************/
//        String str = "write test";//UTF-8 英文字符占一个字节
//        int length = str.getBytes().length;//因此得到的字节长度为10
//        buf.writeBytes(str.getBytes());
//        System.out.println("writable bytes " + buf.writableBytes());
//        System.out.println("readable bytes " + buf.readableBytes());
//
//        /*******************读取数据*********************/
//        char c = (char)buf.readByte();//读取第一个字节，并转换成字符打印
//        System.out.println("c:" + c);
//        System.out.println("writable bytes " + buf.writableBytes());
//        System.out.println("readable bytes " + buf.readableBytes());
//
//        /*******************丢弃已读*********************/
//        buf.discardReadBytes();
//        System.out.println("writable bytes " + buf.writableBytes());
//        System.out.println("readable bytes " + buf.readableBytes());
		
		ByteBuf buf = Unpooled.buffer(0);
		System.out.println("buf init-->" + buf);
		System.out.println("buf init-->" + buf);
		buf.retain();
		byte[] bytes1 = "hello".getBytes();
		byte[] bytes2 = "world".getBytes();
		System.out.println("buf init-->" + buf);

		buf.writeBytes(bytes1);
		buf.writeBytes(bytes2);
		System.out.println("buf write-->" + buf);

		byte[] byte3 = new byte[1];
		buf.readBytes(byte3);
		ByteBuf buf1 = Unpooled.wrappedBuffer(buf);
		byte[] byte4 = new byte[buf1.writerIndex()];
		buf1.readBytes(byte4);
		System.out.println("byte3:" + new String(byte3));
		System.out.println("byte4:" + new String(byte4));
		buf1.resetReaderIndex();
		buf1.readBytes(byte4);

		System.out.println("byte4:" + new String(byte4));

		buf1.clear();
//        System.out.println("buf read-->" + buf);
//        System.out.println("buf read-->" + buf1);
//        buf.discardReadBytes();
//        System.out.println("buf discardReadBytes-->" + buf);
//          
//        buf.clear();
//        buf.retain();
//        System.out.println("buf clear-->" + buf);
//        bytes2="wor".getBytes();
//        buf.writeBytes(bytes1);
//        buf.writeBytes(bytes2);
//        System.out.println("buf write-->" + buf);
//        byte3=new byte[buf.writerIndex()];
//        buf.readBytes(byte3);
//        System.out.println("byte3:" + new String(byte3));
//        System.out.println("buf read-->" + buf);
//        buf.clear();
//        System.out.println("buf clear-->" + buf);
//        Test1();
//        Test2();
//		Test3();
//        Test4();
//        Test5();
//		System.out.println("2737152%160:" + (2737152 % 160));
//
//		int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//		int[] newData;
//		newData = Arrays.copyOf(data, 2);
//		for (int i : newData)
//			System.out.print(i + " ");
		test8("C:\\Users\\Admin\\Desktop\\新建文件夹\\436193136a095550-called.pcm",640);
		System.out.println("分割线====================");
		test8("C:\\Users\\Admin\\Desktop\\新建文件夹\\called.pcm",640);
	}

	public static void Test4() {
		long start = SystemClock.now();
		Map<Integer, Message> cache = new HashMap<Integer, Message>();
		Message msg = new Message();
		for (int i = 0; i < 500000000; i++) {
			Message obj = (Message) msg.clone();
			cache.put(i, obj);
		}
		System.out.println("clone useTime:" + SystemClock.getDelayTime(start));
	}

	public static void Test5() {
		long start = SystemClock.now();
		Map<Integer, Message> cache = new HashMap<Integer, Message>();

		for (int i = 0; i < 5000000; i++) {
			Message msg = new Message();
			cache.put(i, msg);
		}
		System.out.println("new useTime:" + SystemClock.getDelayTime(start));
	}

	public static void Test1() {
//    	  String a = "ccc";
//          String b = "dddd";
//          ByteBuf buf1 = Unpooled.wrappedBuffer(a.getBytes(CharsetUtil.UTF_8));
//          ByteBuf buf2 = Unpooled.wrappedBuffer(b.getBytes(CharsetUtil.UTF_8));
//          CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
//          
//          compositeByteBuf.addComponent(true,buf1);//一定要使用这个方法
//          if (buf2 != null) {
//              compositeByteBuf.addComponent(true, buf2);
//          }
//          int size = compositeByteBuf.readableBytes();
//          byte[] bytes = new byte[size];
//          compositeByteBuf.readBytes(bytes);          
//          String value = new String(bytes,CharsetUtil.UTF_8);
//          System.out.println("composite buff result : " + value);
	}

	public static void Test2() {
		List<String> list = new ArrayList<>();
		list.add("dog");
		list.add("cat");
		list.add("cow");
		System.out.println("===============");
		String[] animals = list.toArray(new String[0]);
		for (String animal : animals) {
			System.out.println(animal);
		}
	}

	public static void Test3() {
		long begin = System.currentTimeMillis();
		for (int i = 0; i < 5000000; i++) {
			Message message = new Message(true);
		}
		System.out.println("创建5w个对象耗时:" + (System.currentTimeMillis() - begin));

		Random random = new Random(5);
		for (int i = 0; i < 10; i++) {
			int receiveLen = (random.nextInt(5) + 5) * 320;
			System.out.println(receiveLen);
		}

	}

	public static void test8(String filePath,int payload) {

		File file = new File(filePath);
		FileChannel channel = null;
		FileInputStream fileInputStream = null;
		int seq = 0;
		if (file.exists()) {
			try {
				fileInputStream = new FileInputStream(file);
				channel = fileInputStream.getChannel();
				// 分配缓冲区
				ByteBuffer byteBuffer = ByteBuffer.allocate(payload);
				while (true) {
					byteBuffer.clear();
					// 将 channel数据写到buffer中
					int len = channel.read(byteBuffer);
					if (len == -1) {
						break;
					}
					byte[] bytes = new byte[len];
					byteBuffer.flip();
					int index = 0;
					while (byteBuffer.hasRemaining()) {
						bytes[index++] = byteBuffer.get();
					}
					logger.info("seq:"+seq+" "+RtpUtil.byte2Hex(bytes));
					seq++;
				}
			} catch (Exception e) {

			} finally {
				try {
					if (fileInputStream != null) {
						fileInputStream.close();
					}
					if (channel != null) {
						channel.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}